package com.clever.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clever.bean.model.OnlineUser;
import com.clever.bean.shopping.Conversation;
import com.clever.bean.shopping.projo.output.ChatMessageDetailVO;
import com.clever.config.RabbitMQConfig;
import com.clever.mapper.ConversationMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import com.clever.mapper.ChatMessageMapper;
import com.clever.bean.shopping.ChatMessage;
import com.clever.service.ChatMessageService;

import javax.annotation.Resource;

/**
 * 聊天记录表服务
 *
 * @Author xixi
 * @Date 2024-04-08 11:11:31
 */
@Service
public class ChatMessageServiceImpl implements ChatMessageService {

    private final static Logger log = LoggerFactory.getLogger(ChatMessageServiceImpl.class);

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Resource
    private ConversationMapper conversationMapper;

    /**
     * 获取会话消息
     *
     * @param senderId   发送者id
     * @param receiverId 接收者id
     */
    @Override
    public List<ChatMessageDetailVO> selectMessageDetailList(String senderId, String receiverId) {
        return chatMessageMapper.selectMessageDetailList(senderId, receiverId);
    }

    /**
     * 阅读消息
     *
     * @param senderId 发送者id
     */
    @Override
    public void read(String senderId, OnlineUser onlineUser) {
        chatMessageMapper.readMessage(senderId, onlineUser.getId());
    }

    /**
     * 发送消息
     *
     * @param senderId   发送者id
     * @param receiverId 接收者id
     * @param message    消息
     */
    @Override
    public ChatMessageDetailVO send(String senderId, String receiverId, String message) {
        ChatMessage senderMessage = new ChatMessage();
        senderMessage.setMessage(message);
        senderMessage.setSenderId(senderId);
        senderMessage.setReceiverId(receiverId);

//        ChatMessage receiverMessage = new ChatMessage();
//        receiverMessage.setMessage(message);
//        receiverMessage.setSenderId(receiverId);
//        receiverMessage.setReceiverId(senderId);

        chatMessageMapper.insert(senderMessage);
//        chatMessageMapper.insert(receiverMessage);

        Conversation receiverConversation = conversationMapper.selectOne(new QueryWrapper<Conversation>().eq("sender_id", receiverId).eq("receiver_id", senderId));
        if (receiverConversation == null) {
            Conversation senderConversation = conversationMapper.selectOne(new QueryWrapper<Conversation>().eq("sender_id", senderId).eq("receiver_id", receiverId));
            Conversation conversation = new Conversation();
            conversation.setReceiverId(senderId);
            conversation.setSenderId(receiverId);
            conversation.setProductId(senderConversation.getProductId());
            conversation.setSessionTime(new Date());
            conversationMapper.insert(conversation);
        }
        return chatMessageMapper.selectMessageDetailById(senderMessage.getId());
    }


    /**
     * 分页查询聊天记录表列表
     *
     * @param pageNumber 页码
     * @param pageSize   每页记录数
     * @param senderId   发送者
     * @param receiverId 接收者
     * @return Page<ChatMessage>
     */
    @Override
    public Page<ChatMessage> selectPage(Integer pageNumber, Integer pageSize, String senderId, String receiverId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(senderId)) {
            queryWrapper.eq("sender_id", senderId);
        }
        if (StringUtils.isNotBlank(receiverId)) {
            queryWrapper.eq("receiver_id", receiverId);
        }
        return chatMessageMapper.selectPage(new Page<ChatMessage>(pageNumber, pageSize), queryWrapper);
    }

    /**
     * 根据id获取聊天记录表
     *
     * @param id id
     * @return ChatMessage 聊天记录表信息
     */
    @Override
    public ChatMessage selectById(String id) {
        return chatMessageMapper.selectById(id);
    }

    /**
     * 根据发送者获取列表
     *
     * @param senderId 发送者
     * @return List<ChatMessage> 聊天记录表列表
     */
    @Override
    public List<ChatMessage> selectListBySenderId(String senderId) {
        return chatMessageMapper.selectList(new QueryWrapper<ChatMessage>().eq("sender_id", senderId).orderByAsc("id"));
    }

    /**
     * 根据接收者获取列表
     *
     * @param receiverId 接收者
     * @return List<ChatMessage> 聊天记录表列表
     */
    @Override
    public List<ChatMessage> selectListByReceiverId(String receiverId) {
        return chatMessageMapper.selectList(new QueryWrapper<ChatMessage>().eq("receiver_id", receiverId).orderByAsc("id"));
    }

    /**
     * 新建聊天记录表
     *
     * @param chatMessage 聊天记录表实体信息
     * @param onlineUser  当前登录用户
     * @return ChatMessage 新建后的聊天记录表信息
     */
    @Override
    public ChatMessage create(ChatMessage chatMessage, OnlineUser onlineUser) {
        chatMessageMapper.insert(chatMessage);
        log.info("聊天记录表, 聊天记录表信息创建成功: userId={}, chatMessageId={}", onlineUser.getId(), chatMessage.getId());
        return chatMessage;
    }

    /**
     * 修改聊天记录表
     *
     * @param chatMessage 聊天记录表实体信息
     * @param onlineUser  当前登录用户
     * @return ChatMessage 修改后的聊天记录表信息
     */
    @Override
    public ChatMessage update(ChatMessage chatMessage, OnlineUser onlineUser) {
        chatMessageMapper.updateById(chatMessage);
        log.info("聊天记录表, 聊天记录表信息修改成功: userId={}, chatMessageId={}", onlineUser.getId(), chatMessage.getId());
        return chatMessage;
    }

    /**
     * 保存聊天记录表
     *
     * @param chatMessage 聊天记录表实体信息
     * @param onlineUser  当前登录用户
     * @return ChatMessage 保存后的聊天记录表信息
     */
    @Override
    public ChatMessage save(ChatMessage chatMessage, OnlineUser onlineUser) {
        if (StringUtils.isNotBlank(chatMessage.getId())) {
            return create(chatMessage, onlineUser);
        }
        return update(chatMessage, onlineUser);
    }

    /**
     * 根据id删除聊天记录表信息
     *
     * @param id         id
     * @param onlineUser 当前登录用户
     */
    @Override
    public void delete(String id, OnlineUser onlineUser) {
        chatMessageMapper.deleteById(id);
        log.info("聊天记录表, 聊天记录表信息删除成功: userId={}, chatMessageId={}", onlineUser.getId(), id);
    }

    /**
     * 根据id列表删除聊天记录表信息
     *
     * @param ids        id列表
     * @param onlineUser 当前登录用户
     */
    @Override
    public void deleteBatchIds(List<String> ids, OnlineUser onlineUser) {
        chatMessageMapper.deleteBatchIds(ids);
        log.info("聊天记录表, 聊天记录表信息批量删除成功: userId={}, count={}, chatMessageIds={}", onlineUser.getId(), ids.size(), ids.toString());
    }

    /**
     * 根据发送者删除
     *
     * @param senderId   发送者
     * @param onlineUser 当前登录用户
     */
    @Override
    public void deleteBySenderId(String senderId, OnlineUser onlineUser) {
        chatMessageMapper.delete(new QueryWrapper<ChatMessage>().eq("sender_id", senderId));
        log.info("聊天记录表, 聊天记录表信息根据senderId删除成功: userId={}, senderId={}", onlineUser.getId(), senderId);
    }

    /**
     * 根据接收者删除
     *
     * @param receiverId 接收者
     * @param onlineUser 当前登录用户
     */
    @Override
    public void deleteByReceiverId(String receiverId, OnlineUser onlineUser) {
        chatMessageMapper.delete(new QueryWrapper<ChatMessage>().eq("receiver_id", receiverId));
        log.info("聊天记录表, 聊天记录表信息根据receiverId删除成功: userId={}, receiverId={}", onlineUser.getId(), receiverId);
    }

    @RabbitListener(queues = RabbitMQConfig.CHAT_QUEUE)
    public void receiveMessage(ChatMessage message) {

    }
}
